
import { _decorator, Component, Node, Vec3 } from 'cc';
import { Utils } from '../data/utils';
import { MonsterView } from './MonsterView';
import { UIManager } from '../ui/UIManager';
import { BattleManager } from '../managers/BattleManager';
import { CustomEventListener } from '../data/CustomEventListener';
import { Constants } from '../data/Constants';
const { ccclass, property } = _decorator;
/**
 * 怪物的控制程序(控制一个怪物)
 */
@ccclass('Monster')
export class Monster extends Component {
    //对视图对象的引用
    private _view: MonsterView = null!;
    //怪物移动到角色时间
    private _speed = 10;
    //初始化视图类对象
    public init(view: MonsterView) {
        this._view = view
        this._view.init(this)
        this._moveToRoadCenter()
    }

    //出生后,向马路中间集合
    private _moveToRoadCenter() {
        //生成随机坐标
        const randomX = Utils.getRandomValueInRange(-8, 8)
        const randomZ = Utils.getRandomValueInRange(-40, 0)
        const myPos = this._view.node.position
        //计算出怪物要移动到的随机坐标
        const targetPos = new Vec3(randomX, myPos.y, randomZ - 40)
        const dis = Math.abs(randomX - myPos.x)
        const time = this._clamp(dis / this._speed, 2, 8)
        //让怪物移动到目标点
        this._view?.MoveToTarget(targetPos, time, this._moveToPlayer.bind(this))
        CustomEventListener.on(Constants.EventName.MONSTER_MOVE, this._moveToPlayer, this)

    }

    //移动到目标
    private _moveToPlayer() {
        if (!BattleManager.instance()._isGameStart || !this._view.node) {
            return;
        }
        //先计算一个马路中间的随机x坐标
        const randomX = Utils.getRandomValueInRange(-3, 3)
        const myPos = this._view.node.position;
        //计算出怪物要移动到的目标点, 即玩家角色的坐标.
        const targetPos = new Vec3(randomX, myPos.y, -6.5);
        const dis = Vec3.distance(myPos, targetPos);
        const time = this._clamp(dis / this._speed, 2, 8);
        //让怪物在指定的时间里移动到目标点
        this._view?.MoveToTarget(targetPos, time, this._gameFail.bind(this))
    }

    //将第一个参数的值夹在第二个和第三个参数的中间
    private _clamp(num: number, min: number, max: number) {
        if (num < min) {
            return min;
        } else if (num > max) {
            return max;
        } else {
            return num
        }
    }
    private _gameFail() {
        console.warn('游戏失败')
        BattleManager.instance().playerDead();
    }

    //停止移动
    public stopMove() {
        this._view.stopMove();
    }
    //删除该怪物.
    public dispose() {
        this._view.dispose()
    }


    //怪物的受伤程序,
    public onHurt() {
        BattleManager.instance().monsterDead(this)
        this.dispose()
    }
}


